package cn.com.guage.dtm.huawei;

import java.util.Arrays;

public class guage_列表合并 {
    public static void main(String[] args) {
        int[] array1 = {1, 3, 5, 7, 9, 18, 21, 23, 201,222,2223};
        int[] array2 = {2, 4, 6, 8, 10, 12, 13, 14, 15, 16, 17, 19, 20, 200};
        int[] merged = merge(array1, array2);
        System.out.println(Arrays.toString(merged));
        System.out.println(Arrays.toString(merge2(array1, array2)));
        int[] merged3 = merge3(array1, array2);
        System.out.println(Arrays.toString(merged3));

    }

    //在Java中，可以通过双指针法高效地合并两个升序数组。以下是实现代码示例：
    public static int[] merge(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int[] result = new int[m + n];

        int i = 0, j = 0, k = 0;

        /**
         *  比较两个数组的元素，将较小的放入结果数组
         */

        while (i < m && j < n) {
            if (nums1[i] <= nums2[j]) {
                result[k++] = nums1[i++];
            } else {
                result[k++] = nums2[j++];
            }
        }
        System.out.println(Arrays.toString(result));

        // 将剩余元素拷贝到结果数组
        while (i < m) {
            result[k++] = nums1[i++];
        }

        while (j < n) {
            result[k++] = nums2[j++];
        }

        return result;
    }

    public static int[] merge2(int[] a, int[] b) {
        int[] res = new int[a.length + b.length];
        for (int i = 0; i < a.length; i++) {
            res[i] = a[i];
        }
        for (int i = 0; i < b.length; i++) {
            res[a.length + i] = b[i];
        }
        Arrays.sort(res);
        return res;
    }


    public static int[] merge3(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        //定义数组指针
        int i = 0;
        int j = 0;
        //定义合并数组指针
        int k = 0;
        int[] result = new int[m + n];
        while (i < m && j < n) {
            if (nums1[i] <= nums2[j]) {
                result[k] = nums1[i];
                k = k + 1;
                i = i + 1;
            } else {
                result[k] = nums2[j];
                k = k + 1;
                j = j + 1;
            }
        }
        while (i < m) {
            result[k] = nums1[i];
            k = k + 1;
            i = i + 1;
        }
        while (j < n) {
            result[k] = nums2[j];
            k = k + 1;
            j = j + 1;
        }
        return result;
    }
}
